<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车辆编号" prop="carCode">
        <el-input
          v-model="queryParams.carCode"
          placeholder="请输入车辆编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="卖家ID" prop="sellerId">
        <el-input
          v-model="queryParams.sellerId"
          placeholder="请输入卖家ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌" prop="brandId">
        <el-select 
          v-model="queryParams.brandId" 
          placeholder="请选择品牌" 
          clearable
          @change="handleQueryBrandChange"
        >
          <el-option
            v-for="brand in brandList"
            :key="brand.id"
            :label="brand.brandName"
            :value="brand.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="车系" prop="seriesId">
        <el-select 
          v-model="queryParams.seriesId" 
          placeholder="请选择车系" 
          clearable
          :disabled="!queryParams.brandId"
        >
          <el-option
            v-for="series in queryFilteredSeriesList"
            :key="series.id"
            :label="series.seriesName"
            :value="series.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="车型名称" prop="modelName">
        <el-input
          v-model="queryParams.modelName"
          placeholder="请输入车型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="首次注册日期" prop="registerTime">
        <el-date-picker clearable
          v-model="queryParams.registerTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择首次注册日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="行驶里程" prop="mileage">
        <el-input
          v-model="queryParams.mileage"
          placeholder="请输入行驶里程"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排量" prop="displacement">
        <el-input
          v-model="queryParams.displacement"
          placeholder="请输入排量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车身颜色" prop="color">
        <el-input
          v-model="queryParams.color"
          placeholder="请输入车身颜色"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车辆类型" prop="carType">
        <el-select v-model="queryParams.carType" placeholder="请选择车辆类型" clearable>
          <el-option
            v-for="item in carTypeDict"
            :key="item.id"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="燃油类型" prop="fuelType">
        <el-select v-model="queryParams.fuelType" placeholder="请选择燃油类型" clearable>
          <el-option
            v-for="item in fuelTypeDict"
            :key="item.id"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="车辆状况" prop="carCondition">
        <el-select v-model="queryParams.carCondition" placeholder="请选择车辆状况" clearable>
          <el-option label="优秀" value="1"></el-option>
          <el-option label="良好" value="2"></el-option>
          <el-option label="一般" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="价格区间" prop="priceRange">
        <el-row :gutter="10">
          <el-col :span="11">
            <el-input
              v-model="queryParams.minPrice"
              placeholder="最低价"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-col>
          <el-col :span="2" style="text-align: center;">
            <span style="color: #606266;">-</span>
          </el-col>
          <el-col :span="11">
            <el-input
              v-model="queryParams.maxPrice"
              placeholder="最高价"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="车辆主图URL" prop="mainPic">
        <el-input
          v-model="queryParams.mainPic"
          placeholder="请输入车辆主图URL"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="success" icon="el-icon-refresh-right" size="mini" @click="refreshDictData">刷新字典</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['car:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['car:info:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['car:info:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleBatchApprove"
          v-hasPermi="['car:info:approve']"
        >批量审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :disabled="multiple"
          @click="handleBatchOffline"
          v-hasPermi="['car:info:offline']"
        >批量下架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['car:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="multipleTable" v-loading="loading" :data="infoList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车辆ID" align="center" prop="id" width="80" />
      <el-table-column label="车辆编号" align="center" prop="carCode" width="140" />
      <el-table-column label="卖家ID" align="center" prop="sellerId" width="80" />
      <el-table-column label="品牌" align="center" prop="brandId" width="100">
        <template slot-scope="scope">
          {{ getBrandName(scope.row.brandId) }}
        </template>
      </el-table-column>
      <el-table-column label="车系" align="center" prop="seriesId" width="120">
        <template slot-scope="scope">
          {{ getSeriesName(scope.row.seriesId) }}
        </template>
      </el-table-column>
      <el-table-column label="车型名称" align="center" prop="modelName" width="180" show-overflow-tooltip />
      <el-table-column label="类型" align="center" prop="carType" width="80">
        <template slot-scope="scope">
          {{ getDictLabel(carTypeDict, scope.row.carType) }}
        </template>
      </el-table-column>
      <el-table-column label="注册日期" align="center" prop="registerTime" width="110">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.registerTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="里程" align="center" prop="mileage" width="80">
        <template slot-scope="scope">
          {{ scope.row.mileage }}万公里
        </template>
      </el-table-column>
      <el-table-column label="排量" align="center" prop="displacement" width="80">
        <template slot-scope="scope">
          {{ scope.row.displacement }}L
        </template>
      </el-table-column>
      <el-table-column label="燃油" align="center" prop="fuelType" width="80">
        <template slot-scope="scope">
          {{ getDictLabel(fuelTypeDict, scope.row.fuelType) }}
        </template>
      </el-table-column>
      <el-table-column label="变速箱" align="center" prop="gearboxType" width="100">
        <template slot-scope="scope">
          {{ getDictLabel(gearboxTypeDict, scope.row.gearboxType) }}
        </template>
      </el-table-column>
      <el-table-column label="颜色" align="center" prop="color" width="80" />
      <el-table-column label="车况" align="center" prop="carCondition" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.carCondition === 1" type="success" size="small">优秀</el-tag>
          <el-tag v-else-if="scope.row.carCondition === 2" type="warning" size="small">良好</el-tag>
          <el-tag v-else-if="scope.row.carCondition === 3" type="info" size="small">一般</el-tag>
          <span v-else>{{ scope.row.carCondition }}</span>
        </template>
      </el-table-column>
      <el-table-column label="售价(万元)" align="center" prop="price" width="100">
        <template slot-scope="scope">
          {{ (scope.row.price / 10000).toFixed(1) }}
        </template>
      </el-table-column>
      <el-table-column label="主图" align="center" prop="mainPic" width="100">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.mainPic"
            :src="scope.row.mainPic"
            :preview-src-list="[scope.row.mainPic]"
            fit="cover"
            style="width: 60px; height: 45px; border-radius: 4px;"
          >
            <div slot="error" class="image-slot-small">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <span v-else>暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="详情描述" align="center" prop="detailDesc" width="150" show-overflow-tooltip />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === -1" type="danger" size="small">审核拒绝</el-tag>
          <el-tag v-else-if="scope.row.status === 0" type="warning" size="small">待审核</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="success" size="small">已上架</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="info" size="small">已售出</el-tag>
          <span v-else>{{ scope.row.status }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220" fixed="right">
        <template slot-scope="scope">
          <!-- 状态流转按钮 -->
          <el-button
            v-if="scope.row.status === 0"
            size="mini"
            type="success"
            icon="el-icon-check"
            @click="handleApprove(scope.row)"
            v-hasPermi="['car:info:approve']"
          >审核通过</el-button>
          <el-button
            v-if="scope.row.status === 0"
            size="mini"
            type="danger"
            icon="el-icon-close"
            @click="handleReject(scope.row)"
            v-hasPermi="['car:info:reject']"
          >审核拒绝</el-button>
          <el-button
            v-if="scope.row.status === 1"
            size="mini"
            type="warning"
            icon="el-icon-download"
            @click="handleOffline(scope.row)"
            v-hasPermi="['car:info:offline']"
          >下架</el-button>
          <el-button
            v-if="scope.row.status === 2"
            size="mini"
            type="primary"
            icon="el-icon-upload2"
            @click="handleOnline(scope.row)"
            v-hasPermi="['car:info:online']"
          >重新上架</el-button>
          <el-button
            v-if="scope.row.status === -1"
            size="mini"
            type="success"
            icon="el-icon-check"
            @click="handleApprove(scope.row)"
            v-hasPermi="['car:info:approve']"
          >重新审核</el-button>
          
          <!-- 基础操作按钮 -->
          <el-dropdown trigger="click" @command="handleCommand">
            <el-button size="mini" type="text">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item 
                :command="{action: 'edit', row: scope.row}"
                icon="el-icon-edit"
              >修改</el-dropdown-item>
              <el-dropdown-item 
                :command="{action: 'delete', row: scope.row}"
                icon="el-icon-delete"
                divided
              >删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车辆基础信息（买车页、详情页）对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车辆编号" prop="carCode">
          <el-input v-model="form.carCode" placeholder="系统自动生成" readonly>
            <el-button slot="append" icon="el-icon-refresh" @click="generateCarCode">重新生成</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="卖家ID" prop="sellerId">
          <el-input v-model="form.sellerId" placeholder="请输入卖家ID" />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select 
            v-model="form.brandId" 
            placeholder="请选择品牌" 
            clearable
            @change="handleBrandChange"
          >
            <el-option
              v-for="brand in brandList"
              :key="brand.id"
              :label="brand.brandName"
              :value="brand.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车系" prop="seriesId">
          <el-select 
            v-model="form.seriesId" 
            placeholder="请选择车系" 
            clearable
            :disabled="!form.brandId"
          >
            <el-option
              v-for="series in filteredSeriesList"
              :key="series.id"
              :label="series.seriesName"
              :value="series.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车型名称" prop="modelName">
          <el-input v-model="form.modelName" placeholder="请输入车型名称" />
        </el-form-item>
        <el-form-item label="车辆类型" prop="carType">
          <el-select v-model="form.carType" placeholder="请选择车辆类型">
            <el-option
              v-for="item in carTypeDict"
              :key="item.id"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="首次注册日期" prop="registerTime">
          <el-date-picker clearable
            v-model="form.registerTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择首次注册日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="行驶里程" prop="mileage">
          <el-input v-model="form.mileage" placeholder="请输入行驶里程" />
        </el-form-item>
        <el-form-item label="排量" prop="displacement">
          <el-input v-model="form.displacement" placeholder="请输入排量" />
        </el-form-item>
        <el-form-item label="燃油类型" prop="fuelType">
          <el-select v-model="form.fuelType" placeholder="请选择燃油类型">
            <el-option
              v-for="item in fuelTypeDict"
              :key="item.id"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="变速箱类型" prop="gearboxType">
          <el-select v-model="form.gearboxType" placeholder="请选择变速箱类型">
            <el-option
              v-for="item in gearboxTypeDict"
              :key="item.id"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车身颜色" prop="color">
          <el-input v-model="form.color" placeholder="请输入车身颜色" />
        </el-form-item>
        <el-form-item label="车辆状况" prop="carCondition">
          <el-select v-model="form.carCondition" placeholder="请选择车辆状况">
            <el-option label="优秀" value="1"></el-option>
            <el-option label="良好" value="2"></el-option>
            <el-option label="一般" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="售价" prop="price">
          <el-input v-model="form.price" placeholder="请输入售价" />
        </el-form-item>
        <el-form-item label="车辆主图" prop="mainPic">
          <image-upload v-model="form.mainPic" :limit="1" :fileSize="5" :fileType="['png', 'jpg', 'jpeg', 'gif']" :isCarImage="true" />
        </el-form-item>
        <el-form-item label="车辆详情描述" prop="detailDesc">
          <el-input v-model="form.detailDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/car/info"
import { listBrand } from "@/api/car/brand"
import { listSeries } from "@/api/car/series"
import { getDictData, getDictLabel, refreshAllDictData } from "@/utils/dictUtils"
import ImageUpload from "@/components/ImageUpload"

export default {
  name: "Info",
  components: {
    ImageUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车辆基础信息（买车页、详情页）表格数据
      infoList: [],
      // 品牌列表数据
      brandList: [],
      // 车系列表数据
      seriesList: [],
      // 过滤后的车系列表（根据选择的品牌）
      filteredSeriesList: [],
      // 查询区域过滤后的车系列表
      queryFilteredSeriesList: [],
      // 字典数据
      carTypeDict: [], // 车辆类型字典
      fuelTypeDict: [], // 燃油类型字典
      gearboxTypeDict: [], // 变速箱类型字典
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        carCode: null,
        sellerId: null,
        brandId: null,
        seriesId: null,
        modelName: null,
        carType: null,
        registerTime: null,
        mileage: null,
        displacement: null,
        fuelType: null,
        gearboxType: null,
        color: null,
        carCondition: null,
        price: null,
        mainPic: null,
        detailDesc: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        carCode: [
          { required: true, message: "车辆编号不能为空", trigger: "blur" }
        ],
        sellerId: [
          { required: true, message: "卖家ID不能为空", trigger: "blur" }
        ],
        brandId: [
          { required: true, message: "品牌ID不能为空", trigger: "blur" }
        ],
        seriesId: [
          { required: true, message: "车系ID不能为空", trigger: "blur" }
        ],
        modelName: [
          { required: true, message: "车型名称不能为空", trigger: "blur" }
        ],
        carType: [
          { required: true, message: "车辆类型不能为空", trigger: "change" }
        ],
        registerTime: [
          { required: true, message: "首次注册日期不能为空", trigger: "blur" }
        ],
        mileage: [
          { required: true, message: "行驶里程不能为空", trigger: "blur" }
        ],
        displacement: [
          { required: true, message: "排量不能为空", trigger: "blur" }
        ],
        fuelType: [
          { required: true, message: "燃油类型不能为空", trigger: "change" }
        ],
        gearboxType: [
          { required: true, message: "变速箱类型不能为空", trigger: "change" }
        ],
        color: [
          { required: true, message: "车身颜色不能为空", trigger: "blur" }
        ],
        carCondition: [
          { required: true, message: "车辆状况不能为空", trigger: "change" }
        ],
        price: [
          { required: true, message: "售价不能为空", trigger: "blur" }
        ],
        mainPic: [
          { required: false, message: "请选择车辆主图", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态：0-待审核，1-已上架，2-已售出不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "发布时间不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getBrandList()
    this.getSeriesList()
    this.loadDictData()
  },
  methods: {
    /** 查询车辆基础信息（买车页、详情页）列表 */
    getList() {
      this.loading = true
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        carCode: null,
        sellerId: null,
        brandId: null,
        seriesId: null,
        modelName: null,
        carType: null,
        registerTime: null,
        mileage: null,
        displacement: null,
        fuelType: null,
        gearboxType: null,
        color: null,
        carCondition: null,
        price: null,
        minPrice: null,
        maxPrice: null,
        mainPic: null,
        detailDesc: null,
        status: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.generateCarCode() // 自动生成车辆编号
      this.open = true
      this.title = "添加车辆基础信息（买车页、详情页）"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getInfo(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改车辆基础信息（买车页、详情页）"
        // 编辑时初始化车系下拉列表
        this.$nextTick(() => {
          this.initFilteredSeriesForEdit()
        })
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除车辆基础信息（买车页、详情页）编号为"' + ids + '"的数据项？').then(function() {
        return delInfo(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('car/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    },
    /** 查询品牌列表 */
    getBrandList() {
      // 传递一个大的pageSize参数来获取所有品牌数据，避免分页限制
      const params = {
        pageNum: 1,
        pageSize: 1000  // 设置足够大的数量以获取所有品牌
      }
      listBrand(params).then(response => {
        this.brandList = response.rows
        console.log('品牌列表数据:', this.brandList)
        console.log('品牌总数:', response.total)
      })
    },
    /** 查询车系列表 */
    getSeriesList() {
      // 传递一个大的pageSize参数来获取所有车系数据，避免分页限制
      const params = {
        pageNum: 1,
        pageSize: 1000  // 设置足够大的数量以获取所有车系
      }
      listSeries(params).then(response => {
        this.seriesList = response.rows
        console.log('车系列表数据:', this.seriesList)
        console.log('车系总数:', response.total)
        
        // 调试：显示前5个车系的详细信息
        if (this.seriesList && this.seriesList.length > 0) {
          console.log('前5个车系的详细信息:')
          this.seriesList.slice(0, 5).forEach((series, index) => {
            console.log(`车系${index + 1}:`, {
              id: series.id,
              seriesName: series.seriesName,
              brandId: series.brandId,
              brandIdType: typeof series.brandId,
              brandName: series.brandName,
              完整对象: series
            })
          })
        }
      })
    },
    /** 根据品牌ID查询车系列表 */
    getSeriesListByBrand(brandId) {
      const params = brandId ? { brandId: brandId } : {}
      listSeries(params).then(response => {
        const filteredSeries = response.rows
        console.log('根据品牌查询的车系列表:', filteredSeries)
        return filteredSeries
      })
    },
    /** 根据品牌ID获取品牌名称 */
    getBrandName(brandId) {
      if (!brandId || !this.brandList || this.brandList.length === 0) {
        return brandId || '-'
      }
      const brand = this.brandList.find(item => item.id === brandId)
      return brand ? brand.brandName : brandId
    },
    /** 根据车系ID获取车系名称 */
    getSeriesName(seriesId) {
      if (!seriesId || !this.seriesList || this.seriesList.length === 0) {
        return seriesId || '-'
      }
      const series = this.seriesList.find(item => item.id === seriesId)
      return series ? series.seriesName : seriesId
    },
    /** 品牌选择变更处理 */
    handleBrandChange(brandId) {
      // 清空车系选择
      this.form.seriesId = null
      // 根据品牌ID过滤车系列表
      this.filterSeriesByBrand(brandId)
    },
    /** 根据品牌ID过滤车系列表 */
    filterSeriesByBrand(brandId) {
      console.log('过滤车系 - 品牌ID:', brandId, '类型:', typeof brandId)
      console.log('车系列表:', this.seriesList)
      
      if (this.seriesList && this.seriesList.length > 0) {
        // 打印前几个车系的brandId信息用于调试
        console.log('前3个车系的brandId:', this.seriesList.slice(0, 3).map(s => ({
          id: s.id,
          seriesName: s.seriesName,
          brandId: s.brandId,
          brandIdType: typeof s.brandId
        })))
      }
      
      if (brandId && this.seriesList && this.seriesList.length > 0) {
        // 使用 == 而不是 === 来避免数据类型不匹配的问题
        this.filteredSeriesList = this.seriesList.filter(series => {
          const match = series.brandId == brandId
          if (!match) {
            console.log(`不匹配: series.brandId(${series.brandId}, ${typeof series.brandId}) != brandId(${brandId}, ${typeof brandId})`)
          }
          return match
        })
        console.log('过滤后的车系列表:', this.filteredSeriesList)
      } else {
        this.filteredSeriesList = []
        console.log('清空车系列表，原因: brandId为空或车系列表为空')
      }
    },
    /** 编辑时初始化车系列表 */
    initFilteredSeriesForEdit() {
      if (this.form.brandId) {
        this.filterSeriesByBrand(this.form.brandId)
      }
    },
    /** 查询区域品牌选择变更处理 */
    handleQueryBrandChange(brandId) {
      // 清空车系选择
      this.queryParams.seriesId = null
      // 根据品牌ID过滤车系列表
      this.filterQuerySeriesByBrand(brandId)
    },
    /** 根据品牌ID过滤查询区域的车系列表 */
    filterQuerySeriesByBrand(brandId) {
      console.log('过滤查询车系 - 品牌ID:', brandId, '类型:', typeof brandId)
      console.log('车系列表:', this.seriesList)
      
      if (this.seriesList && this.seriesList.length > 0) {
        // 打印前几个车系的brandId信息用于调试
        console.log('前3个车系的brandId:', this.seriesList.slice(0, 3).map(s => ({
          id: s.id,
          seriesName: s.seriesName,
          brandId: s.brandId,
          brandIdType: typeof s.brandId
        })))
      }
      
      if (brandId && this.seriesList && this.seriesList.length > 0) {
        // 使用 == 而不是 === 来避免数据类型不匹配的问题
        this.queryFilteredSeriesList = this.seriesList.filter(series => {
          const match = series.brandId == brandId
          if (!match) {
            console.log(`不匹配: series.brandId(${series.brandId}, ${typeof series.brandId}) != brandId(${brandId}, ${typeof brandId})`)
          }
          return match
        })
        console.log('过滤后的查询车系列表:', this.queryFilteredSeriesList)
      } else {
        this.queryFilteredSeriesList = []
        console.log('清空车系列表，原因: brandId为空或车系列表为空')
      }
    },
    /** 下拉菜单命令处理 */
    handleCommand(command) {
      if (command.action === 'edit') {
        this.handleUpdate(command.row)
      } else if (command.action === 'delete') {
        this.handleDelete(command.row)
      }
    },
    /** 审核通过 */
    handleApprove(row) {
      this.$modal.confirm('确认要审核通过该车辆吗？').then(() => {
        return this.updateCarStatus(row.id, 1, '审核通过')
      }).then(() => {
        this.$modal.msgSuccess("审核通过成功")
        this.getList()
      }).catch(() => {})
    },
    /** 审核拒绝 */
    handleReject(row) {
      this.$modal.confirm('确认要拒绝该车辆审核吗？').then(() => {
        return this.updateCarStatus(row.id, -1, '审核拒绝')
      }).then(() => {
        this.$modal.msgSuccess("审核拒绝成功")
        this.getList()
      }).catch(() => {})
    },
    /** 下架车辆 */
    handleOffline(row) {
      this.$modal.confirm('确认要下架该车辆吗？').then(() => {
        return this.updateCarStatus(row.id, 2, '下架')
      }).then(() => {
        this.$modal.msgSuccess("下架成功")
        this.getList()
      }).catch(() => {})
    },
    /** 重新上架 */
    handleOnline(row) {
      this.$modal.confirm('确认要重新上架该车辆吗？').then(() => {
        return this.updateCarStatus(row.id, 1, '重新上架')
      }).then(() => {
        this.$modal.msgSuccess("重新上架成功")
        this.getList()
      }).catch(() => {})
    },
    /** 更新车辆状态的通用方法 */
    updateCarStatus(carId, status, operation) {
      const data = {
        id: carId,
        status: status
      }
      return updateInfo(data)
    },
    /** 批量审核通过 */
    handleBatchApprove() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请先选择要审核的车辆")
        return
      }
      this.$modal.confirm(`确认要批量审核通过这 ${this.ids.length} 辆车吗？`).then(() => {
        const promises = this.ids.map(id => this.updateCarStatus(id, 1, '批量审核通过'))
        return Promise.all(promises)
      }).then(() => {
        this.$modal.msgSuccess("批量审核成功")
        this.getList()
        this.clearSelection()
      }).catch(() => {})
    },
    /** 批量下架 */
    handleBatchOffline() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请先选择要下架的车辆")
        return
      }
      this.$modal.confirm(`确认要批量下架这 ${this.ids.length} 辆车吗？`).then(() => {
        const promises = this.ids.map(id => this.updateCarStatus(id, 2, '批量下架'))
        return Promise.all(promises)
      }).then(() => {
        this.$modal.msgSuccess("批量下架成功")
        this.getList()
        this.clearSelection()
      }).catch(() => {})
    },
    /** 清空选择 */
    clearSelection() {
      this.$refs.multipleTable && this.$refs.multipleTable.clearSelection()
    },
    /** 生成唯一车辆编号 */
    generateCarCode() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')
      const milliseconds = String(now.getMilliseconds()).padStart(3, '0')
      
      // 生成格式：CAR + 年月日 + 时分秒 + 毫秒后两位
      this.form.carCode = `CAR${year}${month}${day}${hours}${minutes}${seconds}${milliseconds.substr(0, 2)}`
      
      console.log('生成的车辆编号:', this.form.carCode)
    },
    /** 加载字典数据 */
    loadDictData() {
      // 使用全局字典管理加载数据
      Promise.all([
        getDictData('car_type'),
        getDictData('fuel_type'),
        getDictData('gearbox_type')
      ]).then(([carTypeDict, fuelTypeDict, gearboxTypeDict]) => {
        this.carTypeDict = carTypeDict
        this.fuelTypeDict = fuelTypeDict
        this.gearboxTypeDict = gearboxTypeDict
        console.log('字典数据加载完成:', {
          carTypeDict: this.carTypeDict,
          fuelTypeDict: this.fuelTypeDict,
          gearboxTypeDict: this.gearboxTypeDict
        })
      }).catch(error => {
        console.error('字典数据加载失败:', error)
        this.$modal.msgError('字典数据加载失败，请刷新页面重试')
      })
    },
    /** 根据字典值获取字典标签 */
    getDictLabel(dictList, value) {
      return getDictLabel(dictList, value)
    },
    /** 刷新字典数据 */
    refreshDictData() {
      this.$modal.loading("正在刷新字典数据...")
      refreshAllDictData().then(() => {
        // 重新加载本页面的字典数据
        this.loadDictData()
        this.$modal.closeLoading()
        this.$modal.msgSuccess("字典数据已刷新")
      }).catch(error => {
        this.$modal.closeLoading()
        console.error('刷新字典数据失败:', error)
        this.$modal.msgError('刷新字典数据失败，请稍后重试')
      })
    }
  }
}
</script>

<style scoped>
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 60px;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
  border-radius: 4px;
}

.image-slot-small {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60px;
  height: 45px;
  background: #f5f7fa;
  color: #909399;
  font-size: 16px;
  border-radius: 4px;
}

.el-image {
  border: 1px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.3s;
}

.el-image:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 表格优化样式 */
::v-deep .el-table {
  font-size: 12px;
}

::v-deep .el-table .cell {
  padding: 0 8px;
}

::v-deep .el-table--small .el-table__cell {
  padding: 4px 0;
}
</style>
